#coding: utf8
import re
from pygeocoder import Geocoder
import datetime
from fresh.YelpMasterDB import YelpMasterDB
from fresh.utils import Utils
import time

class updateGoogleYelp(object):

    host = "mysql2.alwaysdata.com"
    user = "62465_jmgost"
    passw = "sygnium"
    skema = "freshbuzzing_1"

    
    

def main():
    db = YelpMasterDB()
    utils = Utils()
    db.utils=utils
    db.connectDB()
    logLocalName="UPDATE_GOOGLE_YELP"
    try:
        num=0
        utils.logProcessBegin(logLocalName)
        print "logbegin"
        sql = "SELECT ID_REST_SOURCE, DS_REST_ADDRESS_GOOGLE, DS_REST_ZIP_CODE FROM MAST_REST_YELP WHERE NUM_REST_LATITUDE is null or NUM_REST_LONGITUDE is null"
        db.getCursor()
        db.cursor.execute(sql)
        data=db.cursor.fetchall()
        for item in data:
            lat=None
            long=None
            xy=utils.getGoogleCoordinates(item[1],item[2],lat,long)
            if xy is not None:
                location=xy[2]
                lat=xy[0]
                long=xy[1]
                sql = "UPDATE MAST_REST_YELP SET NUM_REST_LATITUDE=%s, NUM_REST_LONGITUDE=%s,AUX_DS_GOOGLE_LOCATION=%s WHERE ID_REST_SOURCE=%s"
                db.cursor.execute(sql,(str(lat),str(long),str(location),item[0]))
                num=num+1
                db.db.commit()
                print str(num)
        
    except Exception,e:
        print "exception"+str(e)
        db.db.rollback()
        utils.logProcessDetail("ERROR: " + str(e), utils.ERROR)

    finally:
        utils.logProcessEnd("End of process updates: " + str(num), utils.DEBUG)
        db.db.close()
    return True





if __name__ == "__main__":
    main()  